import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_countdown_timer/countdown_timer_controller.dart';
import 'package:flutter_countdown_timer/current_remaining_time.dart';
import 'package:flutter_countdown_timer/flutter_countdown_timer.dart';
import 'package:get/get.dart';
import 'package:mall/constant/app_colors.dart';
import 'package:mall/constant/app_dimens.dart';
import 'package:mall/constant/app_strings.dart';
import 'package:mall/constant/text_style.dart';
import 'package:mall/gen/r.dart';
import 'package:mall/modules/business.dart';
import 'package:mall/modules/service/user_service.dart';
import 'package:mall/router/route_names.dart';
import 'package:mall/ui/page/login/widgets/agreement_widget.dart';
import 'package:mall/ui/page/login/widgets/input_widget.dart';
import 'package:mall/ui/widgets/loading_dialog.dart';
import 'package:mall/utils/ext/widget_ext.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mall/utils/hud/hud_util.dart';
import 'package:mall/utils/keyboard/keyboard_util.dart';

class LoginWithPhone extends StatefulWidget {
  @override
  State<LoginWithPhone> createState() => _LoginWithPhoneState();
}

class _LoginWithPhoneState extends State<LoginWithPhone> {
  final TextEditingController _phoneController = TextEditingController();

  final TextEditingController _codeController = TextEditingController();

  int endTime = 0;
  //是否已经获取过验证码了
  RxBool hasGetCode = false.obs;
  Rx<CountdownTimerController> _timerController = Rx(CountdownTimerController(endTime: 0));

  //是否阅读并同意了协议
  RxBool hasReadProtocol = false.obs;

  @override
  void dispose() {
    _timerController.value.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // _userViewModel = Provider.of<UserViewModel>(context);
    // _loginViewModel = LoginViewModel(_userViewModel);
    return Scaffold(
      // title: AppStrings.LOGIN,
      backgroundColor: Colors.white,
      appBar: AppBar(
        actions: [
          TextButton(
              onPressed: () {
                // Get.toNamed(MobileRouteNames.login_password);
                Get.offAndToNamed(MobileRouteNames.login_password);
              },
              child: Text(
                '账号密码登录',
                style: APPTextStyle.color_666666_size_13,
              )),
        ],
      ),

      body: SingleChildScrollView(
        child: Container(
          // alignment: Alignment.centerLeft,
          margin: EdgeInsets.only(left: 33.w, right: 33.w, top: 50),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '验证码登录/注册',
                style: TextStyle(
                  color: AppColors.C_222222,
                  fontSize: 25,
                  fontWeight: FontWeight.bold,
                ),
              ),
              SizedBox(height: 53),
              //输入账号
              _phoneTextField(),
              SizedBox(height: 20),
              //输入验证码
              _code(),
              SizedBox(height: 33),
              //登录
              _loginBtn().onInkwellTap(() => _login(context)),
              SizedBox(height: 18),
              //隐私协议
              AgreementWidget(hasReadProtocol: hasReadProtocol),
            ],
          ),
        ),
      ),
    ).closeKeyboard(context);
  }

  Container _loginBtn() {
    return Container(
      alignment: Alignment.center,
      width: double.infinity,
      height: 50,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(25)),
        color: AppColors.C_FF5722,
      ),
      child: Text('登录/注册', style: TextStyle(color: Colors.white, fontSize: 16)),
    );
  }

  Row _code() {
    return Row(
      children: [
        Expanded(
          child: InputWidget(
            leftIcon: R.image.labePhone.path,
            textField: CupertinoTextField(
              keyboardType: TextInputType.phone,
              placeholder: '请输入验证码',
              maxLength: 6,
              clearButtonMode: OverlayVisibilityMode.editing,
              controller: _codeController,
              decoration: BoxDecoration(
                border: null,
                color: Colors.transparent,
              ),
            ),
          ),
        ),

        SizedBox(width: 10),

        Container(
          width: 112,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(25)),
            border: Border.all(color: AppColors.C_FF5722, width: 0.5),
          ),
          child: Obx(() => CountdownTimer(
                controller: _timerController.value,
                widgetBuilder: (BuildContext context, CurrentRemainingTime? time) {
                  bool hasTime = time != null;
                  return InkWell(
                    onTap: () {
                      if (!hasTime) {
                        _getCode(context);
                      }
                    },
                    child: Container(
                      height: 50,
                      child: Center(
                        child: Text(
                          hasTime
                              ? '${time.sec}s 重新获取'
                              : hasGetCode.value
                                  ? '重新获取'
                                  : '获取验证码',
                          style: TextStyle(fontSize: 16, color: AppColors.C_FF5722),
                        ),
                      ),
                    ),
                  );
                },
              )),
        ),
        // Text(
        //   '获取验证码',
        //   style: TextStyle(color: AppColors.COLOR_FF5722, fontSize: 16),
        // ),
      ],
    );
  }

  Widget _phoneTextField() {
    return InputWidget(
      leftIcon: R.image.labePhone.path,
      textField: CupertinoTextField(
        keyboardType: TextInputType.phone,
        placeholder: '请输入手机号',
        maxLength: 11,
        clearButtonMode: OverlayVisibilityMode.editing,
        controller: _phoneController,
        decoration: BoxDecoration(
          border: null,
          color: Colors.transparent,
        ),
      ),
    );
  }

  //去登录
  void _login(BuildContext context) {
    //判断手机号是否存在
    if (_phoneController.text.isEmpty || _phoneController.text.length != 11) {
      HUDUtil.toast('请输入手机号');
      return;
    }
    //判断验证码是否存在
    if (_codeController.text.isEmpty) {
      HUDUtil.toast('请输入验证码');
      return;
    }
    //判断是否同意了协议
    if (!hasReadProtocol.value) {
      HUDUtil.toast('请阅读并同意协议');
      return;
    }

    HUDUtil.show('登录中...');

    Business.registerAndLogin(mobile: _phoneController.text, code: _codeController.text).then((response) {
      HUDUtil.toast('登录成功');
      Get.back();
    }).catchError((e) {
      HUDUtil.dismiss();
    });
  }

  //获取验证码
  void _getCode(BuildContext context) {
    //判断手机号是否存在
    if (_phoneController.text.isEmpty || _phoneController.text.length != 11) {
      HUDUtil.toast('请输入正确的手机号');
      return;
    }
    UserService.getCode(_phoneController.text).then((response) {
      HUDUtil.toast('验证码已发送');
      endTime = DateTime.now().millisecondsSinceEpoch + 1000 * 60;
      _timerController.value = CountdownTimerController(endTime: endTime);
      hasGetCode.value = true;
    }).catchError((e) {});
  }

  void onEnd() {
    _timerController.value.disposeTimer();
  }
}
